# Copyright (C) 2001-2006 Python Software Foundation

"""A package of tesseract-ocr binding"""

__version__ = '1.0'

__all__ = ['fromfilename', 'fromstring']

import sys, os, re
import time
import tempfile
from cStringIO import StringIO
import subprocess
import Image

def __grayscale(filename, newfilename):
    fp = open(filename, 'rb')
    data = fp.read()
    fp.close()
    im = Image.open(StringIO(data))
    if im.mode=='RGBA':
        im=im.convert('RGB')
    im = im.convert('L')
    im.save(newfilename)
    return True

def __get_tesseract_fullname():
    dirname = os.path.dirname(__file__)
    filename = 'win32\\tesseract.exe' if os.name == 'nt' else 'linux/tesseract'
    os.environ['TESSDATA_PREFIX'] = dirname.rstrip(os.sep) + os.sep
    fullname = os.path.join(dirname, filename)
    return fullname

def __getstatusoutput(args):
    p = subprocess.Popen(args=args, shell=True, stdout=subprocess.PIPE)
    while True:
        if p.poll() == 0:
            break
        else:
            time.sleep(0.1)
    return p.returncode, p.stdout.read()

def fromfilename(filename, language='eng'):
    bmp_filename = tempfile.mktemp(prefix='tesseract_ocr_', suffix='.bmp')
    txt_filename = tempfile.mktemp(prefix='tesseract_ocr_', suffix='.txt')
    if __grayscale(filename, bmp_filename):
        args = [__get_tesseract_fullname(), bmp_filename, txt_filename, '-l', language]
        returncode, output = __getstatusoutput(args)
        if returncode == 0:
            fp = open(txt_filename+'.txt', 'rb')
            text = fp.read().decode('utf8')
            fp.close()
        else:
            text = ''
    else:
        text = None
    #__import__('shutil').move(txt_filename+'.txt', 'tesseract-ocr.txt')
    for filename in (bmp_filename, txt_filename):
        if os.path.exists(filename):
            os.remove(filename)
    return text

def fromstring(string, language='eng'):
    img_filename = tempfile.mktemp(prefix='tesseract_ocr_', suffix='.img')
    fp = open(img_filename, 'wb')
    fp.write(string)
    fp.close()
    text = fromfilename(img_filename, language)
    for filename in (img_filename,):
        if os.path.exists(filename):
            os.remove(filename)
    return text

def test():
    filename = os.path.abspath(sys.argv[1])
    text = fromfilename(filename)
    print repr(text)

if __name__ == '__main__':
    test()